package com.sihai.ehr.web.action.exam;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.*;
import com.sihai.ehr.model.sys.AuditStatus;
import com.sihai.ehr.model.sys.ExaminePeriodEnum;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.model.sys.User;
import com.sihai.ehr.service.*;
import com.sihai.ehr.utils.PeriodUtils;
import com.sihai.ehr.web.action.EHRAction;
import com.sihai.ehr.web.pojo.ExamQualCoerceSetPojo;
import com.sihai.ehr.web.pojo.ExamQualScoreItemPojo;
import com.sihai.ehr.web.pojo.ExamQualScorePojo;
import com.sihai.ehr.web.pojo.ExamStatisticsPojo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

/**
 * 定性考核打分控制器
 * 
 * @author Henry
 * 
 */
@Results({
		@Result(name = "qual_score", location = "exam_qual_score.jsp"),
		@Result(name = "no_score", location = "exam_no_score.jsp"),
		@Result(name = "qual_no_score_list", location = "exam_qual_score_list.jsp"),
		@Result(name = "qual_has_score_list", location = "exam_qual_score_list.jsp"),
		@Result(name = "qual_score_detail", location = "exam_qual_score_detail.jsp"),
		@Result(name = "qual_score_dist_detail", location = "exam_qual_score_dist_detail.jsp"),
		@Result(name = "main", location = "exam_qualset_main.jsp"),
		@Result(name = "qual_dist_score_list", location = "exam_qual_score_dist_list.jsp"),
		@Result(name = "qual_score_browse", location = "exam_qual_score_browse.jsp"),
		@Result(name = "qual_score_browse_user", location = "/WEB-INF/pages/exam/exam_qual_score_browse_user.jsp"),
		@Result(name = "qual_score_browse_detail", location = "/WEB-INF/pages/exam/exam_qual_score_browse_detail.jsp"),
		@Result(name = "qual_score_browse_item_detail", location = "exam_qual_score_browse_detail_inner.jsp") })
public class ExamQualScoreAction extends EHRAction {
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -5701943783326308428L;
	private Log log = LogFactory.getLog(ExamQualScoreAction.class);

	@BeanInject
	private EmployeeService employeeService;
	@BeanInject
	private ExamPeriodService examPeriodService;
	@BeanInject
	private ExamBaseConfigService examBaseConfigService;
	@BeanInject
	private ExamQualScoreService examQualScoreService;
	@BeanInject
	private ExamQualSetService examQualSetService;
	@BeanInject
	private ExamQualStandSetService examQualStandSetService;
	@BeanInject
	private ExamQualItemSetService examQualItemSetService;
	@BeanInject
	private ExamStatisticsService examStatisticsService;
	@BeanInject
	private UserService userService;
	@BeanInject
	private AuditBaseService auditBaseService;
	@BeanInject
	private AuditService auditService;
	@BeanInject
	private ExamPeriodAuditingService examPeriodAuditingService;
	@BeanInject
	private DutyService dutyService;
	@BeanInject
	private OrganizationService organizationService;

	// *********************************
	// -------------控制器属性--------------
	// *********************************

	/** 双月考核需要难证当前的月份必须为 */
	private String mBMonthlyExam = ",1,3,5,7,9,11,";
	/** 季度 */
	private String mSeasonExam = ",1,4,7,10,";
	/** 半年 */
	private String mSemiyearlyExam = ",1,7,";
	private String mAnnuallyExam = ",1,";
	/** 考核周期类型 */
	private ExaminePeriodEnum type;

	/** op 打分明细操作类型 */
	private String op;
	/** 打分员工任职编号 */
	private Long workId;
	private EmployeeinfoWork employeeinfoWork;

	/** 周期编号 */
	private Long periodId;
	/** 选择条件查询的周期描述 */
	private String periodDesc;

	/** 岗位编号 */
	private Long dutyId;

	private String dutyIds;

	/** 原统计百分比率图 */
	private String rawQualset;
	/** 实际统计百分比率图 */
	private String actualQualset;
	/** 定性考核分布设置对象 */
	ExamQualDistSet examQualDistSet;
	/** 定性考核统计表 */
	LimitedList<ExamQualCoerceSetPojo> coerceSetPojos;
	/** 定性考核打分对象 */
	private ExamQualScore examQualScore;
	/** 定性考核打分列表 */
	LimitedList<ExamQualScorePojo> examQualScores;
	/** 定性已经考核打分列表 */
	LimitedList<ExamQualScorePojo> examQualHasScores;

	/** 定性考核打分细节对象 */
	ExamQualScoreDetail examQualScoreDetail;

	LimitedList<ExamQualStandardSet> examQualStandardSets;
	/** 定性考核打分细节列表 */
	LimitedList<ExamQualScoreItemPojo> examQualScoreDetails;

	// qsId,startSocre,endScore
	Float startScore;
	Float endScore;
	ExamPeriod examPeriod;
	List<ExamPeriod> examPeriods;
	LimitedList<ExamStatisticsPojo> examStatisticsPojos;
	private boolean accordDistribution = true; // 符合强制性分布
	private boolean allowGenerateScore = false; // 允许普通分数
	private boolean allowSpecialScore = false;

	@Action("/exam/qual_score")
	@Override
	public String execute() throws Exception {
		if (organizationId == null || organizationId < 0 || type == null) {
			if (log.isInfoEnabled()) {
				log.info("【参数异常】【异常说明:未选择打分的组织结构或者周期类型为空】");
			}
			return "no_score";
		}
		int examLimitDay = 15;
		if (ServletActionContext.getServletContext().getInitParameter(
				"examLimitDay") != null) {
			examLimitDay = Integer.parseInt(ServletActionContext
					.getServletContext().getInitParameter("examLimitDay"));
		}
		boolean isExamCurrent = false;
		int year = 0, month = 0; // 定义选择周期年，月
		try {
			Calendar mCalendar = Calendar.getInstance();
			// 统计结果
			if (periodDesc == null || periodDesc.equals("-1")
					|| periodDesc.equals("0")) {
				// 当前周期
				mCalendar.add(Calendar.MONTH, -1);
				periodId = examPeriodService.getExamPeriodByTypeAndYMonthly(
						type, mCalendar.get(Calendar.YEAR),
						mCalendar.get(Calendar.MONTH) + 1);
				year = mCalendar.get(Calendar.YEAR);
				month = mCalendar.get(Calendar.MONTH) + 1;
				isExamCurrent = true;
			} else if (periodDesc.split("-").length > 0) {
				periodId = examPeriodService.getExamPeriodByTypeAndYMonthly(
						type, Integer.parseInt(periodDesc.split("-")[0]),
						Integer.parseInt(periodDesc.split("-")[1]));
				year = Integer.parseInt(periodDesc.split("-")[0]);
				month = Integer.parseInt(periodDesc.split("-")[1]);
			} else {
				if (log.isInfoEnabled()) {
					log.info("【参数异常】【异常说明:周期值异常,periodDesc:" + periodDesc + "】");
				}
				return "no_score";
			}
			examQualDistSet = examQualSetService.getExamQualDistSet(
					organizationId, type);
			// queryExamQualSetByQualScore
			coerceSetPojos = examQualSetService.queryExamQualSetByStatics(
					organizationId, 0L, periodId, type);
			if (coerceSetPojos != null && coerceSetPojos.size() > 0) {
				rawQualset = "[";
				actualQualset = "[";
				for (ExamQualCoerceSetPojo pojo : coerceSetPojos) {
					rawQualset += "['" + pojo.getName() + "',"
							+ (int) (pojo.getPercentage() * 100) + "]" + ",";
					actualQualset += "['" + pojo.getName() + "',"
							+ (int) (pojo.getActualPercentage() * 100) + "]"
							+ ",";
					// 是否符合强制性分布
					if (pojo.getBalanceNumber() != 0) {
						accordDistribution = false;
					}
				}
				if (rawQualset.length() > 1) {
					rawQualset = rawQualset.substring(0,
							rawQualset.length() - 1);
					actualQualset = actualQualset.substring(0,
							actualQualset.length() - 1);

				}
				rawQualset += "]";
				actualQualset += "]";
			}

			if (dutyIds == null || dutyIds.isEmpty()) {
				// 检测当前时间是否有需要考核的职务
				List<Long> listDutysList = examBaseConfigService
						.searchCurExamDutysByDayLimit(type, examLimitDay,
								isExamCurrent);
				if (listDutysList == null || listDutysList.size() <= 0) {
					return "no_score";
				}
				List<Long> requestDutys = null;
				Organization mOrganization = organizationService.get(organizationId);
				if(getCurrentUser() != null && getCurrentUser().getId() != null && getCurrentUser().getId() > 0){
					requestDutys = readCurrentLoginAuditDutyIds(mOrganization.getTopOrganization() != null ? mOrganization.getTopOrganization().getId() : organizationId, getCurrentUser().getWork().getBaseId().getId());
				}
				StringBuffer sbDutyIds = new StringBuffer();
				for (Long dutyId : listDutysList) {
					//过滤当前员工需要审核的职务
					if(requestDutys != null && requestDutys.size() > 0){
						if(requestDutys.contains(dutyId)){
							sbDutyIds.append(dutyId).append(",");
						}
					}else{
						sbDutyIds.append(dutyId).append(",");
					}
					
				}
				dutyIds = sbDutyIds.substring(0, sbDutyIds.length() - 1);
			}
			Long totalCount = examQualScoreService
					.searchExamDistQualScoreCountByStatus(organizationId,
							dutyIds, type, periodId, 0);
			Long hasCount = examQualScoreService
					.searchExamDistQualScoreCountByStatus(organizationId,
							dutyIds, type, periodId, 1);
			if (totalCount != hasCount) {
				accordDistribution = false;
			}
			
			//检测是否当前登录是第一个审核人
			/*ExamPeriodAuditing periodAuditing = examPeriodAuditingService.getExamPeriodAuditingByUserId(periodId, 
					getCurrentUser().getWork().getBaseId().getId());
			if(periodAuditing != null){
				if(periodAuditing.getFirsterAuditerId().longValue() == getCurrentUser().getWork().getBaseId().getId()){
					allowGenerateScore = true;
				}else{
					allowGenerateScore = false;
				}
			}else{
				allowGenerateScore = true;
			}*/
			examQualScores = examQualScoreService.searchRequestAuditExamQualScores(
					organizationId, dutyIds, type, periodId, year, month, 0,
					createLimit(), createSorter());
			if(examQualScores != null && examQualScores.size() > 0){
				ExamPeriodAuditing periodAuditing = examPeriodAuditingService.getExamPeriodAuditing(periodId, 
						employeeService.getEmployeeinfoWork(examQualScores.get(0).getWorkId()).getDuty().getId());
				if(periodAuditing != null){
					if(periodAuditing.getFirsterAuditerId().longValue() == getCurrentUser().getWork().getBaseId().getId()){
						//if (!accordDistribution) { // 判断是否已经符合强制分布，如果符合不需要检测特殊总数
						allowGenerateScore = true;
					}else{
						allowGenerateScore = false;
					}
				}else{
					allowGenerateScore = true;
				}
				
				//检测是否审核过:只需要读取第一条记录（由于是统一提交)
				// 读取审核信息
				List<List<ExamQualTargetAuditing>> audits = examQualScoreService
						.searchQualScoreTargetAuditings(examQualScores.get(0).getId(),
								null, null);
				// 检查当前登录用户是否可以审核当前结点
				if (audits != null && !audits.isEmpty()) {
					List<? extends AuditingBase> auditBases = audits.get(audits
							.size() - 1);
					if (auditBases != null && auditBases.size() > 0
							&& getCurrentUser() != null && getCurrentUserId() > 0 && getCurrentUser().getId() != null && getCurrentUser().getId() > 0) {
						for(AuditingBase audit : auditBases){
							int i=0;
							Auditing auditNode = audit.getAuditing();
							// 1-指定人审核（employee） 2-指定职务审核（duty） 3-上级领导审核 4-上上级领导审核
							switch (auditNode.getIndicator()) {
							case 1:
								long eid = auditNode.getEmployee().getId()
										.longValue();
								if (eid == getCurrentUser().getWork().getBaseId()
										.getId().longValue()) {
									if (audit.getStatus() == AuditStatus.wait_audit) {
										allowSpecialScore = true;
									}
									if(audit.isLast()){
										lastAuditer = true;
									}
									if(i != 0){
										allowGenerateScore = false;
									}
								}
								break;
							case 2:
								if (auditNode.getDuty().getId().longValue() == getCurrentUser()
										.getWork().getDuty().getId().longValue()) {
									if (audit.getStatus() == AuditStatus.wait_audit) {
										allowSpecialScore = true;
									}
									if(audit.isLast()){
										lastAuditer = true;
									}
									if(i != 0){
										allowGenerateScore = false;
									}
								}
								break;
							case 3:
							case 4:
								Duty duty = userService.findUpDuty(null,
										auditBases, audit); // 查找上级或上上级
								if (duty != null
										&& duty.getId().longValue() == getCurrentUser()
												.getWork().getDuty().getId()
												.longValue()) {
									if (audit.getStatus() == AuditStatus.wait_audit) {
										allowSpecialScore = true;	//修改
									}
									if(audit.isLast()){
										lastAuditer = true;
									}
									if(i != 0){
										allowGenerateScore = false;
									}
								}
								break;
							}
							i++;
						}	//for end
					}
				}else{
					allowSpecialScore = true;
				}
			}else{	//无需要审核的员工时
				//检测当前登录者是否已经特批
				examQualScores = examQualScoreService.searchHasAuditExamQualScores(
						organizationId, dutyIds, type, periodId, year, month, 0,
						createLimit(), createSorter());
				if(examQualScores != null && examQualScores.size() > 0){
					ExamPeriodAuditing periodAuditing = examPeriodAuditingService.getExamPeriodAuditing(periodId, 
							employeeService.getEmployeeinfoWork(examQualScores.get(0).getWorkId()).getDuty().getId());
					if(periodAuditing != null){
						if(periodAuditing.getHasAuditerIds().contains("," + getCurrentUser().getWork().getBaseId().getId() + ",")){
							allowSpecialScore = false;
						}else{
							allowSpecialScore = true;
						}
					}else{
						allowSpecialScore = true;
					}
				}else{
					allowGenerateScore = true;
					allowSpecialScore = true;
				}
			}
		} catch (Exception e) {
			if (log.isInfoEnabled()) {
				log.info("【统计结果异常】【异常说明:" + e.getMessage() + "】");
			}
		}

		return "qual_score";
	}

	/**
	 * 查询未打分列表
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/exam/qual_no_score_list")
	public String queryNOQualScores() throws Exception {
		int examLimitDay = 15;
		if (ServletActionContext.getServletContext().getInitParameter(
				"examLimitDay") != null) {
			examLimitDay = Integer.parseInt(ServletActionContext
					.getServletContext().getInitParameter("examLimitDay"));
		}

		Calendar mCalendar = Calendar.getInstance();
		int year, month; // 定义选择周期年，月
		boolean isExamCurrent = false;
		if (periodDesc == null || periodDesc.equals("-1")
				|| periodDesc.equals("0")) {
			int curMonth = mCalendar.get(Calendar.MONTH) + 1;
			// 检测是否可以考核当前周期
			if (type == ExaminePeriodEnum.bimonthly
					&& !mBMonthlyExam.contains("," + curMonth + ",")) {
				return "no_score";
			} else if (type == ExaminePeriodEnum.season
					&& !mSeasonExam.contains("," + curMonth + ",")) {
				return "no_score";
			} else if (type == ExaminePeriodEnum.semiyearly
					&& !mSemiyearlyExam.contains("," + curMonth + ",")) {
				return "no_score";
			} else if (type == ExaminePeriodEnum.annually
					&& !mAnnuallyExam.contains("," + curMonth + ",")) {
				return "no_score";
			}
			// 当前周期
			mCalendar.add(Calendar.MONTH, -1);
			year = mCalendar.get(Calendar.YEAR);
			month = mCalendar.get(Calendar.MONTH) + 1;
			isExamCurrent = true;
		} else if (periodDesc.split("-").length > 0) {
			year = Integer.parseInt(periodDesc.split("-")[0]);
			month = Integer.parseInt(periodDesc.split("-")[1]);
		} else {
			if (log.isInfoEnabled()) {
				log.info("【参数异常】【异常说明:周期值异常,periodDesc:" + periodDesc + "】");
			}
			return "no_score";
		}
		try {
			periodId = examPeriodService.getExamPeriodByTypeAndYMonthly(type,
					year, month);
			if (dutyIds == null || dutyIds.isEmpty()) {
				// 检测当前时间是否有需要考核的职务
				List<Long> listDutysList = examBaseConfigService
						.searchCurExamDutysByDayLimit(type, examLimitDay,
								isExamCurrent);
				if (listDutysList == null || listDutysList.size() <= 0) {
					return "no_score";
				}
				List<Long> requestDutys = null;
				Organization mOrganization = organizationService.get(organizationId);
				if(getCurrentUser() != null && getCurrentUser().getId() != null && getCurrentUser().getId() > 0){
					requestDutys = readCurrentLoginAuditDutyIds(mOrganization.getTopOrganization() != null ? mOrganization.getTopOrganization().getId() : organizationId, getCurrentUser().getWork().getBaseId().getId());
				}
				StringBuffer sbDutyIds = new StringBuffer();
				for (Long dutyId : listDutysList) {
					//过滤当前员工需要审核的职务
					if(requestDutys != null && requestDutys.size() > 0){
						if(requestDutys.contains(dutyId)){
							sbDutyIds.append(dutyId).append(",");
						}
					}else{
						sbDutyIds.append(dutyId).append(",");
					}
					
				}
				dutyIds = sbDutyIds.substring(0, sbDutyIds.length() - 1);
			}
			// 读取考核周期
			examPeriod = examPeriodService.getExamPeriod(periodId);

			examQualScores = examQualScoreService.searchNotInputExamQualScores(
					organizationId, dutyIds, type, periodId, year, month, -1,
					createLimit(), createSorter());
			if(examQualScores != null && examQualScores.size() > 0){
				if (getCurrentUser() != null && getCurrentUser().getId() != null
						&& getCurrentUser().getId() > 0) {
					ExamPeriodAuditing periodAuditing = examPeriodAuditingService
							.getExamPeriodAuditing(periodId,employeeService.getEmployeeinfoWork(examQualScores.get(0).getWorkId()).getDuty().getId());
					if (periodAuditing != null
							&& getCurrentUser().getWork().getBaseId().getId()
									.longValue() == periodAuditing
									.getFirsterAuditerId().longValue()) {
						if (periodAuditing.getGenerateCommitStatus() == 1) {
							allowGenerateScore = false;
						} else {
							allowGenerateScore = true;
						}
					}
				}
			}else{
				allowGenerateScore = false;
			}

			/* 分页 */
			this.paging(examQualScores);
			/* 设置翻页action */
			this.setPageUrl("exam/qual_no_score_list.xhtml");
		} catch (Exception e) {
			if (log.isInfoEnabled()) {
				log.info("【参数异常】【异常说明:查询未打分列表发生错误，原因：" + e.getMessage() + "】");
			}
		}
		return "qual_no_score_list";
	}

	/**
	 * 查询已打分列表
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/exam/qual_has_score_list")
	public String queryHasQualScores() throws Exception {
		int examLimitDay = 15;
		if (ServletActionContext.getServletContext().getInitParameter(
				"examLimitDay") != null) {
			examLimitDay = Integer.parseInt(ServletActionContext
					.getServletContext().getInitParameter("examLimitDay"));
		}
		Calendar mCalendar = Calendar.getInstance();
		int year, month; // 定义选择周期年，月
		boolean isExamCurrent = false;
		if (periodDesc == null || periodDesc.equals("-1")
				|| periodDesc.equals("0")) {
			int curMonth = mCalendar.get(Calendar.MONTH) + 1;
			// 检测是否可以考核当前周期
			if (type == ExaminePeriodEnum.bimonthly
					&& !mBMonthlyExam.contains("," + curMonth + ",")) {
				return "no_score";
			} else if (type == ExaminePeriodEnum.season
					&& !mSeasonExam.contains("," + curMonth + ",")) {
				return "no_score";
			} else if (type == ExaminePeriodEnum.semiyearly
					&& !mSemiyearlyExam.contains("," + curMonth + ",")) {
				return "no_score";
			} else if (type == ExaminePeriodEnum.annually
					&& !mAnnuallyExam.contains("," + curMonth + ",")) {
				return "no_score";
			}
			// 当前周期
			mCalendar.add(Calendar.MONTH, -1);
			year = mCalendar.get(Calendar.YEAR);
			month = mCalendar.get(Calendar.MONTH) + 1;
			isExamCurrent = true;
		} else if (periodDesc.split("-").length > 0) {
			year = Integer.parseInt(periodDesc.split("-")[0]);
			month = Integer.parseInt(periodDesc.split("-")[1]);
		} else {
			if (log.isInfoEnabled()) {
				log.info("【参数异常】【异常说明:周期值异常,periodDesc:" + periodDesc + "】");
			}
			return "no_score";
		}
		try {
			periodId = examPeriodService.getExamPeriodByTypeAndYMonthly(type,
					year, month);
			if (dutyIds == null || dutyIds.isEmpty()) {
				// 检测当前时间是否有需要考核的职务
				List<Long> listDutysList = examBaseConfigService
						.searchCurExamDutysByDayLimit(type, examLimitDay,
								isExamCurrent);
				if (listDutysList == null || listDutysList.size() <= 0) {
					return "no_score";
				}
				List<Long> requestDutys = null;
				Organization mOrganization = organizationService.get(organizationId);
				if(getCurrentUser() != null && getCurrentUser().getId() != null && getCurrentUser().getId() > 0){
					requestDutys = readCurrentLoginAuditDutyIds(mOrganization.getTopOrganization() != null ? mOrganization.getTopOrganization().getId() : organizationId, getCurrentUser().getWork().getBaseId().getId());
				}
				StringBuffer sbDutyIds = new StringBuffer();
				for (Long dutyId : listDutysList) {
					//过滤当前员工需要审核的职务
					if(requestDutys != null && requestDutys.size() > 0){
						if(requestDutys.contains(dutyId)){
							sbDutyIds.append(dutyId).append(",");
						}
					}else{
						sbDutyIds.append(dutyId).append(",");
					}
					
				}
				dutyIds = sbDutyIds.substring(0, sbDutyIds.length() - 1);
			}

			// 读取考核周期
			examPeriod = examPeriodService.getExamPeriod(periodId);

			examQualScores = examQualScoreService.searchExamQualScores(
					organizationId, dutyIds, type, periodId, year, month, 0,
					createLimit(), createSorter());
			if(examQualScores != null && examQualScores.size() > 0){
				if (getCurrentUser() != null && getCurrentUser().getId() != null
						&& getCurrentUser().getId() > 0) {
					ExamPeriodAuditing periodAuditing = examPeriodAuditingService
							.getExamPeriodAuditing(periodId,employeeService.getEmployeeinfoWork(examQualScores.get(0).getWorkId()).getDuty().getId());
					if (periodAuditing != null
							&& getCurrentUser().getWork().getBaseId().getId()
									.longValue() == periodAuditing
									.getFirsterAuditerId().longValue()) {
						if (periodAuditing.getGenerateCommitStatus() == 1) {
							allowGenerateScore = false;
						} else {
							allowGenerateScore = true;
						}
					}
				}
			}else{
				allowGenerateScore = false;
			}
			/* 分页 */
			this.paging(examQualScores);
			/* 设置翻页action */
			this.setPageUrl("exam/qual_has_score_list.xhtml");
		} catch (Exception e) {
			if (log.isInfoEnabled()) {
				log.info("【参数异常】【异常说明:查询已打分列表发生错误，原因：" + e.getMessage() + "】");
			}
		}
		return "qual_has_score_list";
	}

	/**
	 * 普通提交
	 * <p>
	 * 点击普通提交后，不能在对该期打分数
	 * </p>
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "/exam/post_generatesubmit", results = { @Result(name = "success", type = "plainText") })
	public String postGenerateSubmit() throws Exception {
		int examLimitDay = 15;
		if (ServletActionContext.getServletContext().getInitParameter(
				"examLimitDay") != null) {
			examLimitDay = Integer.parseInt(ServletActionContext
					.getServletContext().getInitParameter("examLimitDay"));
		}
		Calendar mCalendar = Calendar.getInstance();
		boolean isExamCurrent = false;
		int year, month; // 定义选择周期年，月
		if (periodDesc == null || periodDesc.equals("-1")
				|| periodDesc.equals("0")) {
			// 当前周期
			mCalendar.add(Calendar.MONTH, -1);
			periodId = examPeriodService.getExamPeriodByTypeAndYMonthly(type,
					mCalendar.get(Calendar.YEAR),
					mCalendar.get(Calendar.MONTH) + 1);
			isExamCurrent = true;
			year = mCalendar.get(Calendar.YEAR);
			month = mCalendar.get(Calendar.MONTH) + 1;
		} else if (periodDesc.split("-").length > 0) {
			periodId = examPeriodService.getExamPeriodByTypeAndYMonthly(type,
					Integer.parseInt(periodDesc.split("-")[0]),
					Integer.parseInt(periodDesc.split("-")[1]));
			year = Integer.parseInt(periodDesc.split("-")[0]);
			month = Integer.parseInt(periodDesc.split("-")[1]);
		} else {
			if (log.isInfoEnabled()) {
				log.info("【参数异常】【异常说明:周期值异常,periodDesc:" + periodDesc + "】");
			}
			return "no_score";
		}
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			// 处理所有查询条件下的审核业务逻缉
			if (dutyIds == null || dutyIds.isEmpty()) {
				// 检测当前时间是否有需要考核的职务
				List<Long> listDutysList = examBaseConfigService
						.searchCurExamDutysByDayLimit(type,
								examLimitDay, isExamCurrent);
				if (listDutysList == null || listDutysList.size() <= 0) {
					return ERROR;
				}
				List<Long> requestDutys = null;
				Organization mOrganization = organizationService.get(organizationId);
				if(getCurrentUser() != null && getCurrentUser().getId() != null && getCurrentUser().getId() > 0){
					requestDutys = readCurrentLoginAuditDutyIds(mOrganization.getTopOrganization() != null ? mOrganization.getTopOrganization().getId() : organizationId, getCurrentUser().getWork().getBaseId().getId());
				}
				StringBuffer sbDutyIds = new StringBuffer();
				for (Long dutyId : listDutysList) {
					//过滤当前员工需要审核的职务
					if(requestDutys != null && requestDutys.size() > 0){
						if(requestDutys.contains(dutyId)){
							sbDutyIds.append(dutyId).append(",");
						}
					}else{
						sbDutyIds.append(dutyId).append(",");
					}
					
				}
				dutyIds = sbDutyIds
						.substring(0, sbDutyIds.length() - 1);
			}
			// 检测是否还有没有打完的分数
			examQualScores = examQualScoreService
					.searchNotInputExamQualScores(organizationId,
							dutyIds, type, periodId, year, month, -1,
							null, null);
			if (examQualScores != null && examQualScores.size() > 0) {
				// 表示存在没有打完的分数
				response.getWriter().write("NOINPUT");
			}else{
				examQualScores = examQualScoreService
						.searchExamQualScores(organizationId,
								dutyIds, type, periodId, year, month, -1,
								null, null);
				if (examQualScores != null && examQualScores.size() > 0) {
					if (getCurrentUser() != null && getCurrentUser().getId() != null
							&& getCurrentUser().getId() > 0) {
						ExamPeriodAuditing periodAuditing = examPeriodAuditingService
								.getExamPeriodAuditing(periodId,employeeService.getEmployeeinfoWork(examQualScores.get(0).getWorkId()).getDuty().getId());
						if (periodAuditing != null
								&& periodAuditing.getCurrentAuditerId().longValue() == getCurrentUser()
										.getWork().getBaseId().getId().longValue()) {
							if (periodAuditing.getGenerateCommitStatus() <= 0) {
								if (periodAuditing.getFirsterAuditerId().longValue() == getCurrentUser()
										.getWork().getBaseId().getId().longValue()) {
									periodAuditing.setGenerateCommitStatus(1); // 普通提交
									// periodAuditing.setSpecialCommitStatus(1);
									// //也不需要做特批处理
								}
								examPeriodAuditingService
										.saveExamPeriodAuditing(periodAuditing);
								response.getWriter().write("NORMAL");
							} else {
								response.getWriter().write("COMMITED");
							}
						} else {
							response.getWriter().write("NOPERMISSION");
						}
					} else {
						response.getWriter().write("NOPERMISSION");
					}
				}else{
					// 表示存在没有打完的分数
					response.getWriter().write("NOINPUT");
				}
			}
			response.getWriter().flush();
			response.getWriter().close();

		} catch (Exception e) {
			if (log.isInfoEnabled()) {
				log.info("【参数异常】【异常说明:查询已打分列表发生错误，原因：" + e.getMessage() + "】");
			}
		}
		return SUCCESS;
	}

	/**
	 * 特别审批提交
	 * <p>
	 * 点击普通提交后，不能在对该期打分数
	 * </p>
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "/exam/post_specialsubmit", results = { @Result(name = "success", type = "plainText") })
	public String postSpecialSubmit() throws Exception {
		int examLimitDay = 15;
		if (ServletActionContext.getServletContext().getInitParameter(
				"examLimitDay") != null) {
			examLimitDay = Integer.parseInt(ServletActionContext
					.getServletContext().getInitParameter("examLimitDay"));
		}
		Calendar mCalendar = Calendar.getInstance();
		int year, month; // 定义选择周期年，月
		boolean isExamCurrent = false;
		if (periodDesc == null || periodDesc.equals("-1")
				|| periodDesc.equals("0")) {
			// 当前周期
			mCalendar.add(Calendar.MONTH, -1);
			periodId = examPeriodService.getExamPeriodByTypeAndYMonthly(type,
					mCalendar.get(Calendar.YEAR),
					mCalendar.get(Calendar.MONTH) + 1);
			isExamCurrent = true;
			year = mCalendar.get(Calendar.YEAR);
			month = mCalendar.get(Calendar.MONTH) + 1;
		} else if (periodDesc.split("-").length > 0) {
			periodId = examPeriodService.getExamPeriodByTypeAndYMonthly(type,
					Integer.parseInt(periodDesc.split("-")[0]),
					Integer.parseInt(periodDesc.split("-")[1]));
			year = Integer.parseInt(periodDesc.split("-")[0]);
			month = Integer.parseInt(periodDesc.split("-")[1]);
		} else {
			if (log.isInfoEnabled()) {
				log.info("【参数异常】【异常说明:周期值异常,periodDesc:" + periodDesc + "】");
			}
			return "no_score";
		}
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			
			// 处理所有查询条件下的审核业务逻缉
			if (dutyIds == null || dutyIds.isEmpty()) {
				// 检测当前时间是否有需要考核的职务
				List<Long> listDutysList = examBaseConfigService
						.searchCurExamDutysByDayLimit(type,
								examLimitDay, isExamCurrent);
				if (listDutysList == null || listDutysList.size() <= 0) {
					return ERROR;
				}
				List<Long> requestDutys = null;
				Organization mOrganization = organizationService.get(organizationId);
				if(getCurrentUser() != null && getCurrentUser().getId() != null && getCurrentUser().getId() > 0){
					requestDutys = readCurrentLoginAuditDutyIds(mOrganization.getTopOrganization() != null ? mOrganization.getTopOrganization().getId() : organizationId, getCurrentUser().getWork().getBaseId().getId());
				}
				StringBuffer sbDutyIds = new StringBuffer();
				for (Long dutyId : listDutysList) {
					//过滤当前员工需要审核的职务
					if(requestDutys != null && requestDutys.size() > 0){
						if(requestDutys.contains(dutyId)){
							sbDutyIds.append(dutyId).append(",");
						}
					}else{
						sbDutyIds.append(dutyId).append(",");
					}
					
				}
				dutyIds = sbDutyIds
						.substring(0, sbDutyIds.length() - 1);
			}
			// 读取考核周期
			examPeriod = examPeriodService.getExamPeriod(periodId);

			// 检测是否还有没有打完的分数
			examQualScores = examQualScoreService
					.searchNotInputExamQualScores(organizationId,
							dutyIds, type, periodId, year, month, -1,
							null, null);
			if (examQualScores != null && examQualScores.size() > 0) {
				// 表示存在没有打完的分数
				response.getWriter().write("NOINPUT");
			}else{
				examQualScores = examQualScoreService.searchRequestAuditExamQualScores(organizationId, dutyIds,
								type, periodId, year, month, 0, null,
								null);
				if(examQualScores != null && examQualScores.size() > 0){
					//检测是否最后一个
					//检测是否审核过:只需要读取第一条记录（由于是统一提交)
					// 读取审核信息
					List<List<ExamQualTargetAuditing>> audits = examQualScoreService
							.searchQualScoreTargetAuditings(examQualScores.get(0).getId(),
									null, null);
					// 检查当前登录用户是否可以审核当前结点
					if (audits != null && !audits.isEmpty()) {
						// 移出第一个审核人
						List<? extends AuditingBase> auditBases = audits.get(audits
								.size() - 1);
						if (auditBases != null && auditBases.size() > 0
								&& getCurrentUser() != null && getCurrentUserId() > 0 && getCurrentUser().getId() != null && getCurrentUser().getId() > 0) {
							for(AuditingBase audit : auditBases){
								Auditing auditNode = audit.getAuditing();
								// 1-指定人审核（employee） 2-指定职务审核（duty） 3-上级领导审核 4-上上级领导审核
								switch (auditNode.getIndicator()) {
								case 1:
									long eid = auditNode.getEmployee().getId()
											.longValue();
									if (eid == getCurrentUser().getWork().getBaseId()
											.getId().longValue()) {
										if(audit.isLast()){
											lastAuditer = true;
										}
									}
									break;
								case 2:
									if (auditNode.getDuty().getId().longValue() == getCurrentUser()
											.getWork().getDuty().getId().longValue()) {
										if(audit.isLast()){
											lastAuditer = true;
										}
									}
									break;
								case 3:
								case 4:
									Duty duty = userService.findUpDuty(null,
											auditBases, audit); // 查找上级或上上级
									if (duty != null
											&& duty.getId().longValue() == getCurrentUser()
													.getWork().getDuty().getId()
													.longValue()) {
										if(audit.isLast()){
											lastAuditer = true;
										}
									}
									break;
								}
							}	//for end
						}
					}else{
						lastAuditer = false;
					}
					
					// queryExamQualSetByQualScore
					coerceSetPojos = examQualSetService.queryExamQualSetByStatics(
							organizationId, 0L, periodId, type);
					if (coerceSetPojos != null && coerceSetPojos.size() > 0) {
						for (ExamQualCoerceSetPojo pojo : coerceSetPojos) {
							// 是否符合强制性分布
							if (pojo.getBalanceNumber() != 0 && !lastAuditer) {
								accordDistribution = false;
							}
						}
					}
					
					if(!accordDistribution){
						// 表示不符合强制性分布
						response.getWriter().write("NONORMAL");
					} else {
						Long notAuditingCount = examQualScoreService.analyseCountNOCurrentAuditing(organizationId, dutyIds,
										type, periodId, 0, getCurrentUser().getWork().getBaseId().getId().longValue());
						if(notAuditingCount > 0){
							response.getWriter().write("NOAUDITEND");
						}else{
	//						examQualScores = examQualScoreService
	//								.searchRequestAuditExamQualScores(organizationId, dutyIds,
	//										type, periodId, year, month, 0, null,
	//										null);
							if(examQualScores != null && examQualScores.size() > 0){
								ExamPeriodAuditing periodAuditing = examPeriodAuditingService
										.getExamPeriodAuditing(periodId,employeeService.getEmployeeinfoWork(examQualScores.get(0).getWorkId()).getDuty().getId());
								if (periodAuditing != null && getCurrentUser() != null && getCurrentUser().getId() != null && getCurrentUser().getId() > 0
										&& periodAuditing.getCurrentAuditerId().longValue() == getCurrentUser()
												.getWork().getBaseId().getId().longValue()) {
									if (periodAuditing.getSpecialCommitStatus() <= 0) {
										if (periodAuditing.getFirsterAuditerId() != null) {
											Iterator<ExamQualScorePojo> it = examQualScores
													.iterator();
											while (it.hasNext()) {
												ExamQualScorePojo pojo = it.next();
												// 统一处理审核结果
												examQualScore = examQualScoreService
														.getExamQualScore(pojo.getId());
												// 统一事务
												if (examQualScore.getCurrentAuditingId() != null && getCurrentUser() != null && getCurrentUser().getId() != null
														&& getCurrentUser().getId() > 0) {
				//									if (periodAuditing.getFirsterAuditerId().longValue() == examQualScore.getCurrentAuditingId().longValue()) {
													if (periodAuditing.getFirsterAuditerId().longValue() == getCurrentUser().getWork().getBaseId().getId().longValue()) {
														
														// 创建审核结果
														AuditingBase auditing = auditBaseService
																.get(examQualScore
																		.getCurrentAuditingId());
														if (auditing == null
																|| auditing.getId() == null
																|| auditing.getId() <= 0) {
															response.getWriter().write("ERROR");
															;
														}
														// 保存审核结果
														auditing.setStatus(AuditStatus.pass_audit);
														auditBaseService
																.saveAuditing(
																		auditing,
																		AuditType.audit_exam_qual_target
																				.toString());
													} else {
														handleCurrentAudit(
																pojo.getId(),
																examQualScore
																		.getCurrentAuditingId(),
																examQualScore
																		.getCurrentAuditStatus());
													}
												}
											}
											// 表示当前处理过
											periodAuditing.setSpecialCommitStatus(1); // 特殊提交
											periodAuditing.setHasAuditerIds(periodAuditing.getHasAuditerIds() == null ? "," + getCurrentUser().getWork().getBaseId()
													.getId().longValue() + "," :
												periodAuditing.getHasAuditerIds() + getCurrentUser().getWork().getBaseId()
												.getId().longValue() + ",");
											examPeriodAuditingService
													.saveExamPeriodAuditing(periodAuditing);
				
											response.getWriter().write("NORMAL");
										} else {
											response.getWriter().write("NOREQUEST");
										}
									}else{
										response.getWriter().write("COMMITED");
									}
								}else{
									response.getWriter().write("NOPERMISSION");
								}
							} else {
								response.getWriter().write("NOREQUEST");
							}
						}
					}
				}else{
					//没有需要特批的直接通过了
					examQualScores = examQualScoreService.searchHasAuditExamQualScores(
							organizationId, dutyIds, type, periodId, year, month, 0,
							createLimit(), createSorter());
					if(examQualScores != null && examQualScores.size() > 0 && getCurrentUserId() > 0){
						ExamPeriodAuditing periodAuditing = examPeriodAuditingService.getExamPeriodAuditing(periodId, 
								employeeService.getEmployeeinfoWork(examQualScores.get(0).getWorkId()).getDuty().getId());
						if(periodAuditing != null){
							if(periodAuditing.getHasAuditerIds().contains("," + getCurrentUser().getWork().getBaseId().getId() + ",")){
								response.getWriter().write("COMMITED");
							}else{
								response.getWriter().write("NORMAL");
								
								Iterator<ExamQualScorePojo> it = examQualScores
										.iterator();
								while (it.hasNext()) {
									ExamQualScorePojo pojo = it.next();
									// 统一处理审核结果
									examQualScore = examQualScoreService.getExamQualScore(pojo.getId());
									// 统一事务
									if (examQualScore.getCurrentAuditingId() != null && getCurrentUser() != null && getCurrentUser().getId() != null
											&& getCurrentUser().getId() > 0) {
										if (periodAuditing.getFirsterAuditerId().longValue() == getCurrentUser().getWork().getBaseId().getId().longValue()) {
											
											// 创建审核结果
											AuditingBase auditing = auditBaseService
													.get(examQualScore
															.getCurrentAuditingId());
											if (auditing == null
													|| auditing.getId() == null
													|| auditing.getId() <= 0) {
												response.getWriter().write("ERROR");
												;
											}
											// 保存审核结果
											auditing.setStatus(AuditStatus.pass_audit);
											auditBaseService
													.saveAuditing(
															auditing,
															AuditType.audit_exam_qual_target
																	.toString());
										} else {
											handleCurrentAudit(
													pojo.getId(),
													examQualScore
															.getCurrentAuditingId(),
													examQualScore
															.getCurrentAuditStatus());
										}
									}
								}
								
								// 表示当前处理过
								periodAuditing.setSpecialCommitStatus(1); // 特殊提交
								periodAuditing.setHasAuditerIds(periodAuditing.getHasAuditerIds() == null ? "," + getCurrentUser().getWork().getBaseId()
										.getId().longValue() + "," :
									periodAuditing.getHasAuditerIds() + getCurrentUser().getWork().getBaseId()
									.getId().longValue() + ",");
								examPeriodAuditingService
										.saveExamPeriodAuditing(periodAuditing);
							}
						}else{
							response.getWriter().write("NOREQUEST");
						}
					}else{
						response.getWriter().write("NOREQUEST");
					}
				}
			}
			response.getWriter().flush();
			response.getWriter().close();

		} catch (Exception e) {
			if (log.isInfoEnabled()) {
				log.info("【参数异常】【异常说明:查询已打分列表发生错误，原因：" + e.getMessage() + "】");
			}
		}
		return SUCCESS;
	}

	@Action("/exam/qual_dist_score_list")
	public String queryDistQualScores() throws Exception {
		int examLimitDay = 15;
		if (ServletActionContext.getServletContext().getInitParameter(
				"examLimitDay") != null) {
			examLimitDay = Integer.parseInt(ServletActionContext
					.getServletContext().getInitParameter("examLimitDay"));
		}
		Calendar mCalendar = Calendar.getInstance();
		boolean isExamCurrent = false;
		if (periodDesc == null || periodDesc.equals("-1")
				|| periodDesc.equals("0")) {
			// 当前周期
			mCalendar.add(Calendar.MONTH, -1);
			periodId = examPeriodService.getExamPeriodByTypeAndYMonthly(type,
					mCalendar.get(Calendar.YEAR),
					mCalendar.get(Calendar.MONTH) + 1);
			isExamCurrent = true;
		} else if (periodDesc.split("-").length > 0) {
			periodId = examPeriodService.getExamPeriodByTypeAndYMonthly(type,
					Integer.parseInt(periodDesc.split("-")[0]),
					Integer.parseInt(periodDesc.split("-")[1]));
		} else {
			if (log.isInfoEnabled()) {
				log.info("【参数异常】【异常说明:周期值异常,periodDesc:" + periodDesc + "】");
			}
			return "no_score";
		}
		try {
			if (dutyIds == null || dutyIds.isEmpty()) {
				// 检测当前时间是否有需要考核的职务
				List<Long> listDutysList = examBaseConfigService
						.searchCurExamDutysByDayLimit(type, examLimitDay,
								isExamCurrent);
				if (listDutysList == null || listDutysList.size() <= 0) {
					return "no_score";
				}
				List<Long> requestDutys = null;
				Organization mOrganization = organizationService.get(organizationId);
				if(getCurrentUser() != null && getCurrentUser().getId() != null && getCurrentUser().getId() > 0){
					requestDutys = readCurrentLoginAuditDutyIds(mOrganization.getTopOrganization() != null ? mOrganization.getTopOrganization().getId() : organizationId, getCurrentUser().getWork().getBaseId().getId());
				}
				StringBuffer sbDutyIds = new StringBuffer();
				for (Long dutyId : listDutysList) {
					//过滤当前员工需要审核的职务
					if(requestDutys != null && requestDutys.size() > 0){
						if(requestDutys.contains(dutyId)){
							sbDutyIds.append(dutyId).append(",");
						}
					}else{
						sbDutyIds.append(dutyId).append(",");
					}
					
				}
				dutyIds = sbDutyIds.substring(0, sbDutyIds.length() - 1);
			}
			// 读取考核周期
			examPeriod = examPeriodService.getExamPeriod(periodId);

			examQualScores = examQualScoreService.searchExamDistQualScores(
					organizationId, dutyIds, type, periodId, 0, startScore,
					endScore, createLimit(), createSorter());
			if(examQualScores != null && examQualScores.size() > 0){
				if (getCurrentUser() != null && getCurrentUser().getId() != null
						&& getCurrentUser().getId() > 0) {
					ExamPeriodAuditing periodAuditing = examPeriodAuditingService
							.getExamPeriodAuditing(periodId,employeeService.getEmployeeinfoWork(examQualScores.get(0).getWorkId()).getDuty().getId());
					if (periodAuditing != null
							&& getCurrentUser().getWork().getBaseId().getId()
									.longValue() == periodAuditing
									.getFirsterAuditerId().longValue()) {
						if (periodAuditing.getGenerateCommitStatus() == 1) {
							allowGenerateScore = false;
						} else {
							allowGenerateScore = true;
						}
					}
				}
			}else{
				allowGenerateScore = false;
			}
			/* 分页 */
			this.paging(examQualScores);
			/* 设置翻页action */
			this.setPageUrl("exam/qual_dist_score_list.xhtml");
		} catch (Exception e) {
			if (log.isInfoEnabled()) {
				log.info("【参数异常】【异常说明:查询已打分列表发生错误，原因：" + e.getMessage() + "】");
			}
		}
		return "qual_dist_score_list";
	}

	/**
	 * 请求打分或者修改打分
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/exam/qual_score_detail")
	public String handleQualScoreDetail() throws Exception {
		// type=${type}&periodId=${periodId}&workId=${qualscore.workId}
		if (workId == null || workId <= 0) {
			if (log.isErrorEnabled()) {
				log.error("【参数异常】【异常说明:员工任职编号为空】");
			}
		}
		int year = 0, month = 0; // 定义选择周期年，月
		if (periodDesc == null || periodDesc.equals("-1")
				|| periodDesc.equals("0")) {
			// 当前周期
			Calendar mCalendar = Calendar.getInstance();
			mCalendar.add(Calendar.MONTH, -1);
			year = mCalendar.get(Calendar.YEAR);
			month = mCalendar.get(Calendar.MONTH) + 1;
		} else if (periodDesc.split("-").length > 0) {
			year = Integer.parseInt(periodDesc.split("-")[0]);
			month = Integer.parseInt(periodDesc.split("-")[1]);
		}

		periodId = examPeriodService.getExamPeriodByTypeAndYMonthly(type, year,
				month);

		employeeinfoWork = employeeService.getEmployeeinfoWork(workId);
		examQualScore = examQualScoreService.getExamQualScore(periodId, workId);
		Long scoreId = examQualScore == null ? -1 : examQualScore.getId();
		try {
			examQualStandardSets = examQualStandSetService
					.searchExamQualStandardSets(
							employeeinfoWork.getOrganization()
									.getTopOrganization() == null ? employeeinfoWork
									.getOrganization().getId()
									: employeeinfoWork.getOrganization()
											.getTopOrganization().getId(),
							null, null);
			examQualScoreDetails = examQualScoreService
					.searchExamQualScoreDetails(
							scoreId,
							employeeinfoWork.getOrganization()
									.getTopOrganization() == null ? employeeinfoWork
									.getOrganization().getId()
									: employeeinfoWork.getOrganization()
											.getTopOrganization().getId(),
							null, null);

			// 读取配置对象信息
			ExamBaseConfig config = examBaseConfigService
					.getExamBaseConfigByDutyId(employeeinfoWork.getDuty()
							.getId());
			List<Auditing> auditings = auditService.findAudits(employeeinfoWork
					.getOrganization().getTopOrganization().getId(),
					AuditType.audit_exam_qual_target, config.getId());
			if (auditings != null && auditings.size() > 0
					&& getCurrentUser() != null) {
				Auditing mAuditing = auditings.get(0);
				if (mAuditing.getEmployee().getId().longValue() == getCurrentUser()
						.getWork().getBaseId().getId().longValue()) {
					allowGenerateScore = true;
					// 缓存起来
					currentAuditerUserId = mAuditing.getEmployee().getId();
					currentAuditingDutyId = employeeinfoWork.getDuty().getId();
				}
			}
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("【读取打分项目异常】【异常说明:" + e.getMessage() + "】");
			}
			return ERROR;
		}

		return "qual_score_detail";
	}

	/**
	 * 请求特批审核打分或者修改打分
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/exam/qual_score_dist_detail")
	public String handleQualScoreDistDetail() throws Exception {
		// type=${type}&periodId=${periodId}&workId=${qualscore.workId}
		if (workId == null || workId <= 0) {
			if (log.isErrorEnabled()) {
				log.error("【参数异常】【异常说明:员工任职编号为空】");
			}
		}
		employeeinfoWork = employeeService.getEmployeeinfoWork(workId);
		currentAuditingDutyId = employeeinfoWork.getDuty().getId();
		int year = 0, month = 0; // 定义选择周期年，月
		if (periodDesc == null || periodDesc.equals("-1")
				|| periodDesc.equals("0")) {
			// 当前周期
			Calendar mCalendar = Calendar.getInstance();
			mCalendar.add(Calendar.MONTH, -1);
			year = mCalendar.get(Calendar.YEAR);
			month = mCalendar.get(Calendar.MONTH) + 1;
		} else if (periodDesc.split("-").length > 0) {
			year = Integer.parseInt(periodDesc.split("-")[0]);
			month = Integer.parseInt(periodDesc.split("-")[1]);
		}

		periodId = examPeriodService.getExamPeriodByTypeAndYMonthly(type, year,
				month);
		examPeriod = examPeriodService.getExamPeriod(periodId);
		examQualScore = examQualScoreService.getExamQualScore(periodId, workId);
		Long scoreId = examQualScore == null ? -1 : examQualScore.getId();
		try {
			examQualStandardSets = examQualStandSetService
					.searchExamQualStandardSets(
							employeeinfoWork.getOrganization()
									.getTopOrganization() == null ? employeeinfoWork
									.getOrganization().getId()
									: employeeinfoWork.getOrganization()
											.getTopOrganization().getId(),
							null, null);
			examQualScoreDetails = examQualScoreService
					.searchExamQualScoreDetails(
							scoreId,
							employeeinfoWork.getOrganization()
									.getTopOrganization() == null ? employeeinfoWork
									.getOrganization().getId()
									: employeeinfoWork.getOrganization()
											.getTopOrganization().getId(),
							null, null);
			// 读取审核信息
			List<List<ExamQualTargetAuditing>> audits = examQualScoreService
					.searchQualScoreTargetAuditings(examQualScore.getId(),
							null, null);
			if (audits == null || audits.size() <= 0) {
				examQualScoreService.saveQualTargetAuditingProcess(
						examQualScore, 1);
				audits = examQualScoreService.searchQualScoreTargetAuditings(
						examQualScore.getId(), null, null);
			}
			// 检查当前登录用户是否可以审核当前结点
			if (audits != null && !audits.isEmpty()) {
				// 移出第一个审核人
				List<? extends AuditingBase> auditBases = audits.get(audits
						.size() - 1);
				if (auditBases != null && auditBases.size() > 0
						&& getCurrentUser() != null && getCurrentUserId() > 0) {
					AuditingBase audit = auditBases.get(0);
					if (audit.getStatus() == AuditStatus.wait_audit) {
						Auditing auditNode = audit.getAuditing();
						// 1-指定人审核（employee） 2-指定职务审核（duty） 3-上级领导审核 4-上上级领导审核
						switch (auditNode.getIndicator()) {
						case 1:
							long eid = auditNode.getEmployee().getId()
									.longValue();
							if (eid == getCurrentUser().getWork().getBaseId()
									.getId().longValue()) {
								allowSpecialScore = true;
								currentAuditingId = audit.getId();
								// 由于auditing duty为空的BUG,更新一种
								// currentAuditingDutyId =
								// audit.getAuditing().getDuty().getId();
								currentAuditerUserId = auditNode.getEmployee()
										.getId();
							}
							break;
						case 2:
							if (auditNode.getDuty().getId().longValue() == getCurrentUser()
									.getWork().getDuty().getId().longValue()) {
								allowSpecialScore = true;
								currentAuditingId = audit.getId();
								currentAuditerUserId = auditNode.getEmployee()
										.getId();
							}
							break;
						case 3:
						case 4:
							Duty duty = userService.findUpDuty(null,
									auditBases, audit); // 查找上级或上上级
							if (duty != null
									&& duty.getId().longValue() == getCurrentUser()
											.getWork().getDuty().getId()
											.longValue()) {
								allowSpecialScore = true;
								currentAuditingId = audit.getId();
								currentAuditerUserId = auditNode.getEmployee()
										.getId();
							}
							break;
						}
					}
					auditBases.remove(0); // 移出第一个
				}

				checkCanAudit((Duty) null, auditBases);
			}
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("【读取打分项目异常】【异常说明:" + e.getMessage() + "】");
			}
			return ERROR;
		}

		currentAuditType = AuditType.audit_exam_qual_target.toString();
		return "qual_score_dist_detail";
	}

	/**
	 * 请求打分或者修改打分
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/exam/qual_score_browse_detail")
	public String handleQualScoreBrowseDetail() throws Exception {
		// type=${type}&periodId=${periodId}&workId=${qualscore.workId}
		if (workId == null || workId <= 0) {
			if (log.isErrorEnabled()) {
				log.error("【参数异常】【异常说明:员工任职编号为空】");
			}
		}
		if (getParameter("y") == null || getParameter("m") == null) {
			if (log.isErrorEnabled()) {
				log.error("【参数异常】【异常说明:当前考核周期为空】");
			}
			return ERROR;
		}
		employeeinfoWork = employeeService.getEmployeeinfoWork(workId);
		int year = Integer.parseInt(getParameter("y"));
		int month = Integer.parseInt(getParameter("m"));
		periodId = examPeriodService.getExamPeriodByTypeAndYMonthly(type, year,
				month);
		examPeriod = examPeriodService.getExamPeriod(periodId);
		if (examPeriod == null) {
			examPeriod = new ExamPeriod();
			examPeriod.setExamYear(year);
			examPeriod.setExamMonthly(month);
			if (type == ExaminePeriodEnum.monthly) {
				examPeriod.setPeriodName(MessageFormat.format(
						ExaminePeriodEnum.monthly.getPeriodFormat(), year,
						month));
			} else if (type == ExaminePeriodEnum.bimonthly) {
				examPeriod.setPeriodName(MessageFormat.format(
						ExaminePeriodEnum.bimonthly.getPeriodFormat(), year,
						month - 1, month));
			} else if (type == ExaminePeriodEnum.season) {
				examPeriod.setPeriodName(MessageFormat.format(
						ExaminePeriodEnum.season.getPeriodFormat(), year,
						month / 3));
			} else if (type == ExaminePeriodEnum.semiyearly) {
				examPeriod.setPeriodName(MessageFormat.format(
						ExaminePeriodEnum.semiyearly.getPeriodFormat(), year,
						month / 6 > 1 ? "下" : "上"));
			} else {
				examPeriod.setPeriodName(MessageFormat.format(
						ExaminePeriodEnum.annually.getPeriodFormat(), year));
			}
		}
		// examQualScore = examQualScoreService.getExamQualScore(periodId,
		// workId);
		// Long scoreId = examQualScore == null ? -1 : examQualScore.getId();
		// try {
		// examQualStandardSets = examQualStandSetService
		// .searchExamQualStandardSets(
		// employeeinfoWork.getOrganization()
		// .getTopOrganization() == null ? employeeinfoWork
		// .getOrganization().getId()
		// : employeeinfoWork.getOrganization()
		// .getTopOrganization().getId(),
		// null, null);
		// examQualScoreDetails = examQualScoreService
		// .searchExamQualScoreDetails(
		// scoreId,
		// employeeinfoWork.getOrganization()
		// .getTopOrganization() == null ? employeeinfoWork
		// .getOrganization().getId()
		// : employeeinfoWork.getOrganization()
		// .getTopOrganization().getId(),
		// null, null);
		// } catch (Exception e) {
		// if (log.isErrorEnabled()) {
		// log.error("【读取打分项目异常】【异常说明:" + e.getMessage() + "】");
		// }
		// return ERROR;
		// }

		return "qual_score_browse_detail";
	}

	/**
	 * 请求打分或者修改打分
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/exam/qual_score_browse_item_detail")
	public String handleQualScoreBrowseItemDetail() throws Exception {
		// type=${type}&periodId=${periodId}&workId=${qualscore.workId}
		if (workId == null || workId <= 0) {
			if (log.isErrorEnabled()) {
				log.error("【参数异常】【异常说明:员工任职编号为空】");
			}
		}
		if (getParameter("y") == null || getParameter("m") == null) {
			if (log.isErrorEnabled()) {
				log.error("【参数异常】【异常说明:当前考核周期为空】");
			}
			return ERROR;
		}
		employeeinfoWork = employeeService.getEmployeeinfoWork(workId);
		int year = Integer.parseInt(getParameter("y"));
		int month = Integer.parseInt(getParameter("m"));
		periodId = examPeriodService.getExamPeriodByTypeAndYMonthly(type, year,
				month);
		examPeriod = examPeriodService.getExamPeriod(periodId);
		if (examPeriod == null) {
			examPeriod = new ExamPeriod();
			examPeriod.setExamYear(year);
			examPeriod.setExamMonthly(month);
			if (type == ExaminePeriodEnum.monthly) {
				examPeriod.setPeriodName(MessageFormat.format(
						ExaminePeriodEnum.monthly.getPeriodFormat(), year,
						month));
			} else if (type == ExaminePeriodEnum.bimonthly) {
				examPeriod.setPeriodName(MessageFormat.format(
						ExaminePeriodEnum.bimonthly.getPeriodFormat(), year,
						month - 1, month));
			} else if (type == ExaminePeriodEnum.season) {
				examPeriod.setPeriodName(MessageFormat.format(
						ExaminePeriodEnum.season.getPeriodFormat(), year,
						month / 3));
			} else if (type == ExaminePeriodEnum.semiyearly) {
				examPeriod.setPeriodName(MessageFormat.format(
						ExaminePeriodEnum.semiyearly.getPeriodFormat(), year,
						month / 6 > 1 ? "下" : "上"));
			} else {
				examPeriod.setPeriodName(MessageFormat.format(
						ExaminePeriodEnum.annually.getPeriodFormat(), year));
			}
		}
		//更新周期名称中有逗号情况
		try {
			if(examPeriod != null && examPeriod.getPeriodName() != null){
				examPeriod.setPeriodName(examPeriod.getPeriodName().replace(",", ""));
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		examQualScore = examQualScoreService.getExamQualScore(periodId, workId);
		Long scoreId = examQualScore == null ? -1 : examQualScore.getId();
		try {
			examQualStandardSets = examQualStandSetService
					.searchExamQualStandardSets(
							employeeinfoWork.getOrganization()
									.getTopOrganization() == null ? employeeinfoWork
									.getOrganization().getId()
									: employeeinfoWork.getOrganization()
											.getTopOrganization().getId(),
							null, null);
			examQualScoreDetails = examQualScoreService
					.searchExamQualScoreDetails(
							scoreId,
							employeeinfoWork.getOrganization()
									.getTopOrganization() == null ? employeeinfoWork
									.getOrganization().getId()
									: employeeinfoWork.getOrganization()
											.getTopOrganization().getId(),
							null, null);
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("【读取打分项目异常】【异常说明:" + e.getMessage() + "】");
			}
			return ERROR;
		}

		return "qual_score_browse_item_detail";
	}

	@Action(value = "/exam/post_qualscore", results = { @Result(name = "success", type = "plainText") })
	public String postQualScore() throws Exception {
		if (workId == null || workId <= 0 || type == null) {
			return ERROR;
		}
		if (getParameter("rawTotalScore") == null) {
			return ERROR;
		}
		Float rawTotalScore = Float.parseFloat(getParameter("rawTotalScore"));
		if (getParameterValues("itemId") == null
				|| getParameterValues("itemId").length <= 0) {
			return ERROR;
		}
		if (getParameterValues("txt_rawScore") == null
				|| getParameterValues("txt_rawScore").length <= 0) {
			return ERROR;
		}
		Long scoreId = getParameter("scoreId") == null ? -1 : Long
				.parseLong(getParameter("scoreId"));
		// 检测周期-添加周期
		ExamPeriod examPeriod;
		EmployeeinfoWork vWork = employeeService.getEmployeeinfoWork(workId);

		int year = 0, month = 0; // 定义选择周期年，月
		if (periodDesc == null || periodDesc.equals("-1")
				|| periodDesc.equals("0")) {
			// 当前周期
			Calendar mCalendar = Calendar.getInstance();
			mCalendar.add(Calendar.MONTH, -1);
			year = mCalendar.get(Calendar.YEAR);
			month = mCalendar.get(Calendar.MONTH) + 1;
		} else if (periodDesc.split("-").length > 0) {
			year = Integer.parseInt(periodDesc.split("-")[0]);
			month = Integer.parseInt(periodDesc.split("-")[1]);
		}

		periodId = examPeriodService.getExamPeriodByTypeAndYMonthly(type, year,
				month);
		if (periodId <= 0) {
			try {
				examPeriod = new ExamPeriod();
				examPeriod.setExamYear(year);
				examPeriod.setExamMonthly(month);
				examPeriod.setPeriodType(type);
				if (type == ExaminePeriodEnum.monthly) {
					examPeriod.setPeriodName(MessageFormat.format(
							type.getPeriodFormat(), year, month)); // 月数是从０开始
				} else if (type == ExaminePeriodEnum.bimonthly) {
					examPeriod.setPeriodName(MessageFormat.format(
							type.getPeriodFormat(), year, month - 1, month));
				} else if (type == ExaminePeriodEnum.season) {
					int examCurMonth = month;
					examPeriod.setPeriodName(MessageFormat.format(type
							.getPeriodFormat(), year, examCurMonth >= 10 ? 4
							: (examCurMonth >= 7 ? 3 : (examCurMonth >= 4 ? 2
									: 1))));
				} else if (type == ExaminePeriodEnum.semiyearly) {
					int examCurMonth = month;
					examPeriod.setPeriodName(MessageFormat.format(type
							.getPeriodFormat(), year, examCurMonth >= 7 ? "下"
							: "上"));
				} else if (type == ExaminePeriodEnum.annually) {
					examPeriod.setPeriodName(MessageFormat.format(
							type.getPeriodFormat(), year));
				}
				periodId = examPeriodService.saveExamPeriod(examPeriod);

			} catch (Exception e) {
				if (log.isErrorEnabled()) {
					log.error("【添加周期异常】【原因：" + e.getMessage() + "】");
				}
				return ERROR;
			}
		} else {
			examPeriod = examPeriodService.getExamPeriod(periodId);
		}
		// 添加或修改分数
		ExamQualScore vScore = new ExamQualScore();
		if (scoreId > 0) {
			vScore.setId(scoreId);
		}
		vScore.setRawScore(rawTotalScore);
		vScore.setScore(rawTotalScore);
		vScore.setExamPeriod(examPeriod);
		vScore.setEmployeeinfoWork(vWork);
		vScore.setStatus(0);// 表示打分
		try {
			examQualScoreService.saveExamQualScore(vScore);
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("【添加打分异常】【原因：" + e.getMessage() + "】");
			}
			return ERROR;
		}

		// 添加或者修改分数项目
		try {
			String[] arrayItems = getParameterValues("itemId");
			String[] arrayValues = getParameterValues("txt_rawScore");
			for (int i = 0; i < arrayItems.length; i++) {
				ExamQualScoreDetail vScoreDetail = examQualScoreService
						.getExamQualScoreDetailByScItemId(vScore.getId(),
								Long.parseLong(arrayItems[i]));
				if (vScoreDetail == null) {
					vScoreDetail = new ExamQualScoreDetail();
					vScoreDetail.setExamScore(vScore);
					vScoreDetail.setExamQualItemSet(examQualItemSetService
							.get(Long.parseLong(arrayItems[i])));
				}
				vScoreDetail.setRawScore(Float.parseFloat(arrayValues[i]));
				examQualScoreService.saveExamQualScoreDetail(vScoreDetail);
			}
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("【添加打分细节异常】【原因：" + e.getMessage() + "】");
			}
			return ERROR;
		}
		// 普通打分，只能第一个审核人，所有只需要打第一个人时添加当前职务　审批员工流程
		ExamPeriodAuditing periodAuditing = examPeriodAuditingService
				.getExamPeriodAuditing(periodId, currentAuditingDutyId);
		if (periodAuditing == null && currentAuditingDutyId > 0
				&& currentAuditerUserId > 0) {
			periodAuditing = new ExamPeriodAuditing();
			periodAuditing.setExamPeriod(examPeriod);
			periodAuditing.setDuty(dutyService.get(currentAuditingDutyId));
			periodAuditing.setCurrentAuditerId(currentAuditerUserId); // currentAuditerUserId
			periodAuditing.setFirsterAuditerId(currentAuditerUserId); // 第一个打分人
			examPeriodAuditingService.saveExamPeriodAuditing(periodAuditing);
		}

		// 添加或者修改员工分数统计
		try {
			ExamStatistics vExamStatistics = examStatisticsService
					.getExamStatistics(periodId, workId);
			ExamBaseConfig vConfig = examBaseConfigService
					.getExamBaseConfigByDutyId(vWork.getDuty().getId());
			if (vExamStatistics == null) {
				vExamStatistics = new ExamStatistics();
				vExamStatistics.setEmployeeinfoWork(vWork);
				vExamStatistics.setExamPeriod(examPeriod);
				vExamStatistics.setExamBaseConfig(vConfig);
			}
			vExamStatistics.setQualScore(rawTotalScore);
			// 读取上一期考核分数
			Float prevScore = examStatisticsService.getExamPrevScore(type,
					workId, periodId);

			if (vExamStatistics.getQuanScore() != null
					&& vExamStatistics.getQuanScore() > 0) {
				Float scoreFloat = rawTotalScore
						* vConfig.getPercentageQualitative() / 100
						+ vExamStatistics.getQuanScore()
						* vConfig.getPercentageQuantitative() / 100;
				vExamStatistics.setScore(scoreFloat);
				if (prevScore > 0) {
					vExamStatistics.setPrevScore(prevScore);
				} else {
					vExamStatistics.setPrevScore(scoreFloat);
				}
			}
			// 如果定性比例为0，则总分即为定量部分的分数
			Float quanPercent = vExamStatistics.getExamBaseConfig()
					.getPercentageQuantitative();
			if (quanPercent == null || quanPercent.longValue() <= 0) {
				vExamStatistics.setScore(rawTotalScore);
				vExamStatistics.setPrevScore(prevScore > 0 ? prevScore
						: rawTotalScore);
			}

			examStatisticsService.saveExamStatistics(vExamStatistics);
		} catch (Exception e) {
			log.error(e);
			return ERROR;
		}
		return SUCCESS;
	}

	/**
	 * 打分特批
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "/exam/post_qualdistscore", results = { @Result(name = "success", type = "plainText") })
	public String postQualDistScore() throws Exception {
		if (workId == null || workId <= 0 || type == null) {
			return ERROR;
		}
		if (getParameter("adjustTotalScore") == null) {
			return ERROR;
		}
		Float adjustTotalScore = Float
				.parseFloat(getParameter("adjustTotalScore"));
		if (getParameterValues("itemId") == null
				|| getParameterValues("itemId").length <= 0) {
			return ERROR;
		}
		if (getParameterValues("txt_adjustScore") == null
				|| getParameterValues("txt_adjustScore").length <= 0) {
			return ERROR;
		}
		Long scoreId = getParameter("scoreId") == null ? -1 : Long
				.parseLong(getParameter("scoreId"));
		// 检测周期-添加周期
		ExamPeriod examPeriod;
		EmployeeinfoWork vWork = employeeService.getEmployeeinfoWork(workId);
		int year = 0, month = 0; // 定义选择周期年，月
		if (periodDesc == null || periodDesc.equals("-1")
				|| periodDesc.equals("0")) {
			// 当前周期
			Calendar mCalendar = Calendar.getInstance();
			mCalendar.add(Calendar.MONTH, -1);
			year = mCalendar.get(Calendar.YEAR);
			month = mCalendar.get(Calendar.MONTH) + 1;
		} else if (periodDesc.split("-").length > 0) {
			year = Integer.parseInt(periodDesc.split("-")[0]);
			month = Integer.parseInt(periodDesc.split("-")[1]);
		}

		periodId = examPeriodService.getExamPeriodByTypeAndYMonthly(type, year,
				month);
		if (periodId <= 0) {
			try {
				examPeriod = new ExamPeriod();
				examPeriod.setExamYear(year);
				examPeriod.setExamMonthly(month);
				examPeriod.setPeriodType(type);
				if (type == ExaminePeriodEnum.monthly) {
					examPeriod.setPeriodName(MessageFormat.format(
							type.getPeriodFormat(), year, month)); // 月数是从０开始
				} else if (type == ExaminePeriodEnum.bimonthly) {
					examPeriod.setPeriodName(MessageFormat.format(
							type.getPeriodFormat(), year, month - 1, month));
				} else if (type == ExaminePeriodEnum.season) {
					int examCurMonth = month;
					examPeriod.setPeriodName(MessageFormat.format(type
							.getPeriodFormat(), year, examCurMonth >= 10 ? 4
							: (examCurMonth >= 7 ? 3 : (examCurMonth >= 4 ? 2
									: 1))));
				} else if (type == ExaminePeriodEnum.semiyearly) {
					int examCurMonth = month;
					examPeriod.setPeriodName(MessageFormat.format(type
							.getPeriodFormat(), year, examCurMonth >= 7 ? "下"
							: "上"));
				} else if (type == ExaminePeriodEnum.annually) {
					examPeriod.setPeriodName(MessageFormat.format(
							type.getPeriodFormat(), year));
				}
				periodId = examPeriodService.saveExamPeriod(examPeriod);

			} catch (Exception e) {
				if (log.isErrorEnabled()) {
					log.error("【添加周期异常】【原因：" + e.getMessage() + "】");
				}
				return ERROR;
			}
		} else {
			examPeriod = examPeriodService.getExamPeriod(periodId);
		}
		// 添加或修改分数
		ExamQualScore vScore = examQualScoreService.getExamQualScore(scoreId);
		if (vScore == null) {
			if (log.isErrorEnabled()) {
				log.error("【查询定性打分异常】【原因：还没有进行过原始打分】");
			}
			return ERROR;
		}
		vScore.setAdjustScore(adjustTotalScore);
		vScore.setScore(adjustTotalScore);
		vScore.setCurrentAuditingId(currentAuditingId);
		vScore.setCurrentAuditerId(currentAuditerUserId);
		vScore.setCurrentAuditStatus(AuditStatus.within_audit); // 表示打分通过向上提交审核
		try {
			examQualScoreService.saveExamQualScore(vScore);
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("【添加打分异常】【原因：" + e.getMessage() + "】");
			}
			return ERROR;
		}

		// 添加或者修改分数项目
		try {
			String[] arrayItems = getParameterValues("itemId");
			String[] arrayValues = getParameterValues("txt_adjustScore");
			for (int i = 0; i < arrayItems.length; i++) {
				ExamQualScoreDetail vScoreDetail = examQualScoreService
						.getExamQualScoreDetailByScItemId(vScore.getId(),
								Long.parseLong(arrayItems[i]));
				if (vScoreDetail == null) {
					vScoreDetail = new ExamQualScoreDetail();
					vScoreDetail.setExamScore(vScore);
					vScoreDetail.setExamQualItemSet(examQualItemSetService
							.get(Long.parseLong(arrayItems[i])));
				}
				vScoreDetail.setAdjustScore(Float.parseFloat(arrayValues[i]));
				examQualScoreService.saveExamQualScoreDetail(vScoreDetail);
			}
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("【添加打分细节异常】【原因：" + e.getMessage() + "】");
			}
			return ERROR;
		}
		/*
		 * // 添加或者修改员工分数统计 try { ExamStatistics vExamStatistics =
		 * examStatisticsService .getExamStatistics(periodId, workId);
		 * ExamBaseConfig vConfig = examBaseConfigService
		 * .getExamBaseConfigByDutyId(vWork.getDuty().getId()); if
		 * (vExamStatistics == null) { vExamStatistics = new ExamStatistics();
		 * vExamStatistics.setEmployeeinfoWork(vWork);
		 * vExamStatistics.setExamPeriod(examPeriod);
		 * vExamStatistics.setExamBaseConfig(vConfig); }
		 * vExamStatistics.setQualScore(adjustTotalScore); if
		 * (vExamStatistics.getQuanScore() != null &&
		 * vExamStatistics.getQuanScore() > 0) { Float scoreFloat =
		 * adjustTotalScore vConfig.getPercentageQualitative() / 100 +
		 * vExamStatistics.getQuanScore() vConfig.getPercentageQuantitative() /
		 * 100; vExamStatistics.setScore(scoreFloat);
		 * 
		 * // 读取上一期考核分数 Float prevScore =
		 * examStatisticsService.getExamPrevScore(type, workId, periodId); if
		 * (prevScore > 0) { vExamStatistics.setPrevScore(prevScore); } else {
		 * vExamStatistics.setPrevScore(scoreFloat); }
		 * 
		 * }
		 * 
		 * examStatisticsService.saveExamStatistics(vExamStatistics); } catch
		 * (Exception e) { return ERROR; }
		 */
		/*
		 * // 创建审核结果 if (currentAuditingId <= 0 || scoreId <= 0) { return ERROR;
		 * } AuditingBase auditing = auditBaseService.get(currentAuditingId); if
		 * (auditing == null || auditing.getId() == null || auditing.getId() <=
		 * 0) { return ERROR; } // 保存审核结果
		 * auditing.setStatus(AuditStatus.pass_audit);
		 * auditBaseService.saveAuditing(auditing,
		 * AuditType.audit_exam_qual_target.toString());
		 */
		/*ExamPeriodAuditing periodAuditing = examPeriodAuditingService
				.getExamPeriodAuditing(periodId, currentAuditingDutyId);
		if (periodAuditing != null
				&& periodAuditing.getCurrentAuditerId().longValue() == currentAuditerUserId
						.longValue()) {
			if (periodAuditing.getFirsterAudtingId() == null
					|| periodAuditing.getFirsterAudtingId() <= 0) {
				examPeriodAuditingService
						.saveExamPeriodAuditing(periodAuditing);
			}
		}*/

		return SUCCESS;
	}

	/**
	 * 查询定性考核历史记录
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/exam/qual_score_browse")
	public String queryHistoryQualScore() throws Exception {
		if (organizationId == null || dutyId == null) {
			if (log.isErrorEnabled()) {
				log.error("【查询定性考核历史行为时发生异常】【原因：部门或岗位为空】");
			}
			return ERROR;
		}
		try {
			Calendar mCalendar = Calendar.getInstance();
			examPeriods = PeriodUtils.getLateThreeExamPeriodTOReverse(type,
					mCalendar.get(Calendar.YEAR),
					mCalendar.get(Calendar.MONTH) + 1);
			if (examPeriods != null) {
				examStatisticsPojos = examStatisticsService
						.searchExamStatisticsPojos(1, organizationId, dutyId,
								type, examPeriods, createLimit(),
								createSorter());
				/* 分页 */
				this.paging(examStatisticsPojos);
				/* 设置翻页action */
				this.setPageUrl("exam/qual_score_browse.xhtml");
			}
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("【查询定性考核历史行为时发生异常】【原因：" + e.getMessage() + "】");
			}
		}
		return "qual_score_browse";
	}

	// add.wxn-------------------
	// 查找个人的定性考核历史记录
	@Action("/public/qual_score_browse_user")
	public String queryUserHistoryQualScore() throws Exception {
		Long userId = getCurrentUserId();
		if (userId == null || userId <= 0) {
			return "qual_score_browse_user";
		}
		User user = userService.getUser(userId);
		if (user == null) {
			if (log.isErrorEnabled()) {
				log.error("【查询定性考核历史行为时发生异常】【原因：部门或岗位为空】");
			}
			return ERROR;
		}
		topOrganizationName = user.getWork().getOrganization()
				.getTopOrganization() == null ? user.getWork()
				.getOrganization().getFullName() : user.getWork()
				.getOrganization().getTopOrganization().getFullName();
		if (type == null) {
			type = ExaminePeriodEnum.monthly;
		}
		try {
			Calendar mCalendar = Calendar.getInstance();
			examPeriods = PeriodUtils.getLateThreeExamPeriodTOReverse(type,
					mCalendar.get(Calendar.YEAR),
					mCalendar.get(Calendar.MONTH) + 1);
			if (examPeriods != null) {
				examStatisticsPojos = examStatisticsService
						.searchExamStatisticsPojoForUser(1, user.getWork()
								.getId(), type, examPeriods);
			}
		} catch (Exception e) {
			e.printStackTrace();
			if (log.isErrorEnabled()) {
				log.error("【查询定性考核历史行为时发生异常】【原因：" + e.getMessage() + "】");
			}
		}
		return "qual_score_browse_user";
	}

	@Action("/public/qual_score_browse_detail")
	public String queryUserHistoryQualDScoreByYear() throws Exception {
		Long userId = getCurrentUserId();
		if (userId == null || userId <= 0) {
			return "qual_score_browse_user";
		}
		User user = userService.getUser(userId);
		if (user == null) {
			if (log.isErrorEnabled()) {
				log.error("【查询定性考核历史行为时发生异常】【原因：部门或岗位为空】");
			}
			return ERROR;
		}
		workId = user.getWork().getId();

		return handleQualScoreBrowseDetail();
	}

	/** 定性考核分数特批审核 */
	@Action(value = "/public/qual_score_dist_audit", results = { @Result(name = "success", type = "plainText") })
	public String audit() throws Exception {

		// "currentAuditingId":${currentAuditingId},
		// "organizationId":"${organizationId}",
		// "currentAuditType":"${currentAuditType}",
		// "auditStatus":$("#audit_select").val(),
		// "scoreId":$("#scoreId").val()

		Long scoreId = getParameter("scoreId") == null ? 0 : Long
				.parseLong(getParameter("scoreId"));
		int auditStatus = getParameter("auditStatus") == null ? 0 : Integer
				.parseInt(getParameter("auditStatus"));
		if (currentAuditingId <= 0 || scoreId <= 0) {
			return ERROR;
		}
		// 处理当前审核人流程
		// handleCurrentAudit(scoreId,currentAuditingId,auditStatus);

		examQualScore = examQualScoreService.getExamQualScore(scoreId);
		// 保存当前缓存审批
		examPeriod = examQualScore.getExamPeriod();
		periodId = examPeriod.getId();
		workId = examQualScore.getEmployeeinfoWork().getId();
		/*
		 * if (auditStatus < 3) { examPeriod.setEndSpecialAudit(1);
		 * examPeriodService.saveExamPeriod(examPeriod); // 更新周期特批审核标识 }
		 */
		if (auditStatus == 1) { // 表示审核通过:更新分数
			examQualScore.setStatus(1); // 表示审核结束
			examQualScore.setCurrentAuditingId(currentAuditingId);
			examQualScore.setCurrentAuditerId(currentAuditerUserId);
			examQualScore.setCurrentAuditStatus(AuditStatus.pass_audit);
			examQualScoreService.saveExamQualScore(examQualScore);
			// 添加或者修改员工分数统计
			try {
				ExamStatistics vExamStatistics = examStatisticsService
						.getExamStatistics(periodId, workId);
				ExamBaseConfig vConfig = examBaseConfigService
						.getExamBaseConfigByDutyId(examQualScore
								.getEmployeeinfoWork().getDuty().getId());
				if (vExamStatistics == null) {
					vExamStatistics = new ExamStatistics();
					vExamStatistics.setEmployeeinfoWork(examQualScore
							.getEmployeeinfoWork());
					vExamStatistics.setExamPeriod(examPeriod);
					vExamStatistics.setExamBaseConfig(vConfig);
				}
				vExamStatistics.setQualScore(examQualScore.getAdjustScore());
				if (vExamStatistics.getQuanScore() != null
						&& vExamStatistics.getQuanScore() > 0) {
					Float scoreFloat = examQualScore.getAdjustScore()
							* vConfig.getPercentageQualitative() / 100
							+ vExamStatistics.getQuanScore()
							* vConfig.getPercentageQuantitative() / 100;
					vExamStatistics.setScore(scoreFloat);

					// 读取上一期考核分数
					Float prevScore = examStatisticsService.getExamPrevScore(
							type, workId, periodId);
					if (prevScore > 0) {
						vExamStatistics.setPrevScore(prevScore);
					} else {
						vExamStatistics.setPrevScore(scoreFloat);
					}

				}

				examStatisticsService.saveExamStatistics(vExamStatistics);
			} catch (Exception e) {
				return ERROR;
			}
		} else if (auditStatus == 2) {
			examQualScore.setStatus(1); // 表示审核结束
			examQualScore.setCurrentAuditingId(currentAuditingId);
			examQualScore.setCurrentAuditerId(currentAuditerUserId);
			examQualScore.setCurrentAuditStatus(AuditStatus.reject_audit);
			examQualScoreService.saveExamQualScore(examQualScore);
			
			// 还原员工分数统计
			try {
				ExamStatistics vExamStatistics = examStatisticsService
						.getExamStatistics(periodId, workId);
				ExamBaseConfig vConfig = examBaseConfigService
						.getExamBaseConfigByDutyId(examQualScore
								.getEmployeeinfoWork().getDuty().getId());
				if (vExamStatistics == null) {
					vExamStatistics = new ExamStatistics();
					vExamStatistics.setEmployeeinfoWork(examQualScore
							.getEmployeeinfoWork());
					vExamStatistics.setExamPeriod(examPeriod);
					vExamStatistics.setExamBaseConfig(vConfig);
				}
				vExamStatistics.setQualScore(examQualScore.getRawScore());
				if (vExamStatistics.getQuanScore() != null
						&& vExamStatistics.getQuanScore() > 0) {
					Float scoreFloat = examQualScore.getRawScore()
							* vConfig.getPercentageQualitative() / 100
							+ vExamStatistics.getQuanScore()
							* vConfig.getPercentageQuantitative() / 100;
					vExamStatistics.setScore(scoreFloat);

					// 读取上一期考核分数
					Float prevScore = examStatisticsService.getExamPrevScore(
							type, workId, periodId);
					if (prevScore > 0) {
						vExamStatistics.setPrevScore(prevScore);
					} else {
						vExamStatistics.setPrevScore(scoreFloat);
					}

				}

				examStatisticsService.saveExamStatistics(vExamStatistics);
			} catch (Exception e) {
				return ERROR;
			}
		} else {
			examQualScore.setCurrentAuditingId(currentAuditingId);
			examQualScore.setCurrentAuditerId(currentAuditerUserId);
			examQualScore.setCurrentAuditStatus(AuditStatus.within_audit); // 审核中
			examQualScoreService.saveExamQualScore(examQualScore);
			
			// 还原员工分数统计
			try {
				ExamStatistics vExamStatistics = examStatisticsService
						.getExamStatistics(periodId, workId);
				ExamBaseConfig vConfig = examBaseConfigService
						.getExamBaseConfigByDutyId(examQualScore
								.getEmployeeinfoWork().getDuty().getId());
				if (vExamStatistics == null) {
					vExamStatistics = new ExamStatistics();
					vExamStatistics.setEmployeeinfoWork(examQualScore
							.getEmployeeinfoWork());
					vExamStatistics.setExamPeriod(examPeriod);
					vExamStatistics.setExamBaseConfig(vConfig);
				}
				vExamStatistics.setQualScore(examQualScore.getRawScore());
				if (vExamStatistics.getQuanScore() != null
						&& vExamStatistics.getQuanScore() > 0) {
					Float scoreFloat = examQualScore.getRawScore()
							* vConfig.getPercentageQualitative() / 100
							+ vExamStatistics.getQuanScore()
							* vConfig.getPercentageQuantitative() / 100;
					vExamStatistics.setScore(scoreFloat);

					// 读取上一期考核分数
					Float prevScore = examStatisticsService.getExamPrevScore(
							type, workId, periodId);
					if (prevScore > 0) {
						vExamStatistics.setPrevScore(prevScore);
					} else {
						vExamStatistics.setPrevScore(scoreFloat);
					}

				}

				examStatisticsService.saveExamStatistics(vExamStatistics);
			} catch (Exception e) {
				return ERROR;
			}
		}

		// 　处理当前审核流程
		ExamPeriodAuditing periodAuditing = examPeriodAuditingService
				.getExamPeriodAuditing(periodId, currentAuditingDutyId);
		if (periodAuditing != null && currentAuditingDutyId > 0
				&& currentAuditerUserId > 0) {
			periodAuditing.setCurrentAuditerId(currentAuditerUserId); // currentAuditerUserId
			// periodAuditing.setGenerateCommitStatus(0);
			periodAuditing.setSpecialCommitStatus(0);
			examPeriodAuditingService.saveExamPeriodAuditing(periodAuditing);
		}

		return SUCCESS;
	}

	private void handleCurrentAudit(Long scoreId, Long curAuditingId,
			AuditStatus auditStatus) {
		AuditingBase auditing = auditBaseService.get(curAuditingId);
		if (auditing == null || auditing.getId() == null
				|| auditing.getId() <= 0) {
			return;
		}
		// 保存审核结果
		auditing.setStatus(auditStatus);
		auditBaseService.saveAuditing(auditing,
				AuditType.audit_exam_qual_target.toString());
		if (auditStatus == auditStatus.pass_audit || auditStatus == auditStatus.reject_audit) {
			// 检测是否其它审批人员也统一提交
			// 读取审核信息
			List<List<ExamQualTargetAuditing>> audits = examQualScoreService
					.searchQualScoreTargetAuditings(scoreId, null, null);
			if (audits != null && !audits.isEmpty()) {
				// 移出第一个审核人
				List<? extends AuditingBase> auditBases = audits.get(audits
						.size() - 1);
				if (auditBases != null && auditBases.size() > 0) {
					Iterator it = auditBases.iterator();
					while (it.hasNext()) {
						AuditingBase audit = (AuditingBase) it.next();
						if (audit.getAuditing().getId() != auditing
								.getAuditing().getId()) {
							it.remove();
						} else {
							it.remove();
							break;
						}
					}
					// it = auditBases.iterator();
					// 统一提交后面的
					while (it.hasNext()) {
						AuditingBase audit = (AuditingBase) it.next();
						audit.setStatus(AuditStatus.pass_audit);
						auditBaseService.saveAuditing(audit,
								AuditType.audit_exam_qual_target.toString());
					}
				}
			}
		}
	}
	
	/**
	 * 读取当前登录者的审核职务集
	 * @param orgId
	 * @param userId
	 * @return
	 */
	private List<Long> readCurrentLoginAuditDutyIds(Long orgId, Long userId){
		List<Long> canAuditDuty = new ArrayList<Long>();
		List<Auditing> listAuditings = auditService.findAuditsTIDByCurrentLoginUserId(orgId, AuditType.audit_exam_qual_target, userId);
		if(listAuditings != null && listAuditings.size() > 0){
			Iterator<Auditing> it = listAuditings.iterator();
			while(it.hasNext()){
				Auditing mAuditing = it.next();
				if(mAuditing.getAuditingTargetId() != null && mAuditing.getAuditingTargetId() > 0){
					ExamBaseConfig mBaseConfig = examBaseConfigService.get(mAuditing.getAuditingTargetId());
					if(mBaseConfig != null){
						canAuditDuty.add(mBaseConfig.getDuty().getId());
					}
				}
			}
		}
		return canAuditDuty;
	}

	public int getHistory_list_type() {
		// return history_list_type;
		return 1;
	}

	private String topOrganizationName;

	public String getTopOrganizationName() {
		return topOrganizationName;
	}

	/****************************
	 * property segement.
	 ***************************/

	public String getOp() {
		return op;
	}

	public void setOp(String op) {
		this.op = op;
	}

	public Long getWorkId() {
		return workId;
	}

	public void setWorkId(Long workId) {
		this.workId = workId;
	}

	public void setEmployeeinfoWork(EmployeeinfoWork employeeinfoWork) {
		this.employeeinfoWork = employeeinfoWork;
	}

	public EmployeeinfoWork getEmployeeinfoWork() {
		return employeeinfoWork;
	}

	public ExaminePeriodEnum getType() {
		return type;
	}

	public void setType(ExaminePeriodEnum type) {
		this.type = type;
	}

	public Long getPeriodId() {
		return periodId;
	}

	public void setPeriodId(Long periodId) {
		this.periodId = periodId;
	}

	public void setPeriodDesc(String periodDesc) {
		this.periodDesc = periodDesc;
	}

	public String getPeriodDesc() {
		return periodDesc;
	}

	public Long getDutyId() {
		return dutyId;
	}

	public void setDutyId(Long dutyId) {
		this.dutyId = dutyId;
	}

	public String getDutyIds() {
		return dutyIds;
	}

	public void setDutyIds(String dutyIds) {
		this.dutyIds = dutyIds;
	}

	public String getRawQualset() {
		return rawQualset;
	}

	public void setRawQualset(String rawQualset) {
		this.rawQualset = rawQualset;
	}

	public String getActualQualset() {
		return actualQualset;
	}

	public void setActualQualset(String actualQualset) {
		this.actualQualset = actualQualset;
	}

	public void setExamQualScore(ExamQualScore examQualScore) {
		this.examQualScore = examQualScore;
	}

	public ExamQualScore getExamQualScore() {
		return examQualScore;
	}

	public ExamQualDistSet getExamQualDistSet() {
		return examQualDistSet;
	}

	public void setExamQualDistSet(ExamQualDistSet examQualDistSet) {
		this.examQualDistSet = examQualDistSet;
	}

	public LimitedList<ExamQualCoerceSetPojo> getCoerceSetPojos() {
		return coerceSetPojos;
	}

	public void setCoerceSetPojos(
			LimitedList<ExamQualCoerceSetPojo> coerceSetPojos) {
		this.coerceSetPojos = coerceSetPojos;
	}

	public LimitedList<ExamQualScorePojo> getExamQualScores() {
		return examQualScores;
	}

	public void setExamQualScores(LimitedList<ExamQualScorePojo> examQualScores) {
		this.examQualScores = examQualScores;
	}

	public LimitedList<ExamQualScorePojo> getExamQualHasScores() {
		return examQualHasScores;
	}

	public void setExamQualHasScores(
			LimitedList<ExamQualScorePojo> examQualHasScores) {
		this.examQualHasScores = examQualHasScores;
	}

	public ExamQualScoreDetail getExamQualScoreDetail() {
		return examQualScoreDetail;
	}

	public void setExamQualScoreDetail(ExamQualScoreDetail examQualScoreDetail) {
		this.examQualScoreDetail = examQualScoreDetail;
	}

	public LimitedList<ExamQualStandardSet> getExamQualStandardSets() {
		return examQualStandardSets;
	}

	public void setExamQualStandardSets(
			LimitedList<ExamQualStandardSet> examQualStandardSets) {
		this.examQualStandardSets = examQualStandardSets;
	}

	public LimitedList<ExamQualScoreItemPojo> getExamQualScoreDetails() {
		return examQualScoreDetails;
	}

	public void setExamQualScoreDetails(
			LimitedList<ExamQualScoreItemPojo> examQualScoreDetails) {
		this.examQualScoreDetails = examQualScoreDetails;
	}

	public Float getStartScore() {
		return startScore;
	}

	public void setStartScore(Float startScore) {
		this.startScore = startScore;
	}

	public Float getEndScore() {
		return endScore;
	}

	public void setEndScore(Float endScore) {
		this.endScore = endScore;
	}

	public ExamPeriod getExamPeriod() {
		return examPeriod;
	}

	public void setExamPeriod(ExamPeriod examPeriod) {
		this.examPeriod = examPeriod;
	}

	public List<ExamPeriod> getExamPeriods() {
		return examPeriods;
	}

	public void setExamPeriods(List<ExamPeriod> examPeriods) {
		this.examPeriods = examPeriods;
	}

	public void setExamStatisticsPojos(
			LimitedList<ExamStatisticsPojo> examStatisticsPojos) {
		this.examStatisticsPojos = examStatisticsPojos;
	}

	public LimitedList<ExamStatisticsPojo> getExamStatisticsPojos() {
		return examStatisticsPojos;
	}

	public boolean isAccordDistribution() {
		return accordDistribution;
	}

	public void setAccordDistribution(boolean accordDistribution) {
		this.accordDistribution = accordDistribution;
	}

	public boolean isAllowGenerateScore() {
		return allowGenerateScore;
	}

	public void setAllowGenerateScore(boolean allowGenerateScore) {
		this.allowGenerateScore = allowGenerateScore;
	}

	public boolean isAllowSpecialScore() {
		return allowSpecialScore;
	}

	public void setAllowSpecialScore(boolean allowSpecialScore) {
		this.allowSpecialScore = allowSpecialScore;
	}
}
